package com.giornoadd.timex.controller;

import java.sql.Date;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.giornoadd.timex.dao.DepartmentManager;
import com.giornoadd.timex.dao.TimesheetManager;
import com.giornoadd.timex.model.Department;
import com.giornoadd.timex.model.Employee;
import com.giornoadd.timex.model.Timesheet;
import com.giornoadd.timex.util.ApplicationSecurityManager;
import com.giornoadd.timex.util.DateUtil;

/**
 * Controller class for the "Enter Hours" screen
 * @author anil
 */
@Controller
public class EnterHoursController {

	@Autowired
    private TimesheetManager timesheetManager = null;
	@Autowired
    private DepartmentManager departmentManager = null;
	@Autowired
    private ApplicationSecurityManager applicationSecurityManager;
    public static final String TID = "tid";

    /**
     * Returns a new instance of Timesheet object if "tid" HTTP parameter is
     * specified; other returns instance of object in database matching the
     * value of the "tid" parameter.
     * @see Timesheet
     */
    @RequestMapping("/enterhour/{id}")    
    protected ModelAndView getEnterHour(HttpSession session,@PathVariable  int id, Model model)
    {
    	Timesheet timesheet;
    	List<Department> departments = departmentManager.getDepartments();
        timesheet = timesheetManager.getTimesheet(id,false);
        if (timesheet == null) return null;
        model.addAttribute("timesheet", timesheet != null ? timesheet : new Timesheet());
        model.addAttribute("departments", departments);
        return new ModelAndView("enterhours");
    }
    
    @RequestMapping(method=RequestMethod.GET, value="/enterhours")
    public ModelAndView getEnterhours(HttpSession session, Model model) {
    	List<Department> departments = departmentManager.getDepartments();
    	Timesheet timesheet;
    	timesheet = new Timesheet();
        Employee employee = (Employee) applicationSecurityManager
                .getEmployee(session);
        timesheet.setEmployeeId(employee.getEmployeeId());
        timesheet.setStatusCode("P");
        timesheet.setPeriodEndingDate(DateUtil.getCurrentPeriodEndingDate());
        model.addAttribute("timesheet", timesheet != null ? timesheet : new Timesheet());
        model.addAttribute("departments", departments);
        return new ModelAndView("enterhours");
    }
    
	  /**
	   * Saves Timesheet command object using 
	   * timesheetManager.saveTimesheet(timesheet);
	   * @see TimesheetManager
	   */
    @RequestMapping(method=RequestMethod.POST)
	  public ModelAndView onSubmit(@RequestHeader(value="X-Requested-With", required=false) String requestedWith, 
	          @Valid Timesheet timesheet,
	          BindingResult result, 
	          HttpSession session, 
	          Model model)
	  {
    	Employee employee = (Employee) applicationSecurityManager.getEmployee(session);
    	Calendar cal = Calendar.getInstance();
    	timesheet.setEmployeeId(employee.getEmployeeId());
    	timesheet.setPeriodEndingDate(cal.getTime());
    	timesheetManager.saveTimesheet(timesheet);
    	session.setAttribute("message", "message.enterhours.savesuccess");
    	return new ModelAndView(new RedirectView("timesheet"));
	  }
//
//    /**
//     * Registers the MinutesPropertyEditor
//     */
//    protected void initBinder(
//            HttpServletRequest request,
//            ServletRequestDataBinder binder) throws Exception
//    {
//        binder.registerCustomEditor(int.class, new MinutesPropertyEditor());
//    }
//
//    /**
//     * Returns Hashmap containing a list of all Department databse records
//     * @see com.visualpatterns.timex.model.Department
//     */
//    protected Map referenceData(HttpServletRequest request) throws Exception
//    {
//        HashMap model = new HashMap();
//        model.put("departments", departmentManager.getDepartments());
//
//        return model;
//    }
//
//    /**
//     * Saves Timesheet command object using 
//     * timesheetManager.saveTimesheet(timesheet);
//     * @see TimesheetManager
//     */
//    protected ModelAndView onSubmit(
//            HttpServletRequest request,
//            HttpServletResponse response,
//            Object command,
//            BindException errors)
//    {
//        Timesheet timesheet = (Timesheet) command;
//        timesheetManager.saveTimesheet(timesheet);
//        request.getSession().setAttribute(
//                "message",
//                getMessageSourceAccessor().getMessage(
//                        "message.enterhours.savesuccess"));
//        return new ModelAndView(getSuccessView());
//    }

    public TimesheetManager getTimesheetManager()
    {
        return timesheetManager;
    }

    public void setTimesheetManager(TimesheetManager timesheetManager)
    {
        this.timesheetManager = timesheetManager;
    }

    public DepartmentManager getDepartmentManager()
    {
        return departmentManager;
    }

    public void setDepartmentManager(DepartmentManager departmentManager)
    {
        this.departmentManager = departmentManager;
    }

    public ApplicationSecurityManager getApplicationSecurityManager()
    {
        return applicationSecurityManager;
    }

    public void setApplicationSecurityManager(
            ApplicationSecurityManager applicationSecurityManager)
    {
        this.applicationSecurityManager = applicationSecurityManager;
    }
}
